This is one page of the R Handbook for Epidemiologists, but is being printed as a stand-alone page.

You can find the complete handbook on Github

Pivoting

Overview

(pivoting/melting etc.) Transforming datasets from wide-to-long, or long-to-wide…

https://datacarpentry.org/r-socialsci/03-dplyr-tidyr/index.html

Wide-to-long

Transforming a dataset from wide to long

Data

We start with data that is in a wide format, e.g. our linelist.

DT::datatable(linelist, rownames = FALSE, filter="top", options = list(pageLength = 5, scrollX=T) )

pivot_longer()

#tidyr::pivot_longer(linelist, dplyr::vars(-age, -date_of_hospitalisation), names_to = "variable", values_to = "value" )

Result

Long-to-wide

dplyr pivot_wider()

Data

Pivot wider

Result